import { sendEmailCode } from '@/api/flow/auth';

export default {
  data() {
    return {
      // send code
      isSendCode: false,
      codeText: 'Verification code sent',
      interval: null,
      time: 60
    };
  },

  beforeDestroy() {
    window.clearInterval(this.interval);
  },

  methods: {
    resetCodeStatus() {
      this.isSendCode = false;

      this.time = 60;

      this.codeText = 'Verification code sent';

      window.clearInterval(this.interval);
    },

    // sendCode
    sendCode(f = 'email', data) {
      const fields = Array.isArray(f) ? f : [f];

      return new Promise((resolve, reject) => {
        this.form.validateFields(fields, (errors, values) => {
          if (!errors) {
            this.isSendCode = true;

            sendEmailCode(data)
              .then(() => {
                this.interval = window.setInterval(() => {
                  this.codeText = `${this.time}s resend verification`;
                  if (this.time-- <= 0) {
                    this.time = 60;
                    this.codeText = 'Resend verification code';
                    this.isSendCode = false;
                    window.clearInterval(this.interval);
                    // return false;
                  }
                }, 1000);
                resolve(data);
              })
              .catch((error) => {
                this.time = 60;
                this.isSendCode = false;
                reject(error);
              });
          }
        });
      });
    }
  }
};
